package com.example.listviewtest;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.support.design.widget.FloatingActionButton;

import org.litepal.LitePal;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    //testgit2e
    private List<Contact> contactList = new ArrayList<>();
    private ListView listView = null;
    private ContactAdapter adapter=null;


    @Override
    protected void onResume() {
        super.onResume();
        contactList.clear();
        List<Contact> contacts= LitePal.findAll(Contact.class);
        for(Contact contact : contacts) {
            //Log.d("MainActivity", "Contact name is " + contact.getName());
            contact.setImageId(R.drawable.contact9);
            contactList.add(contact);
        }
        adapter.notifyDataSetChanged();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initContacts();
        adapter = new ContactAdapter(
                MainActivity.this, R.layout.contact_item, contactList);
        listView = (ListView) findViewById(R.id.list_view);
        listView.setAdapter(adapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Contact contact = contactList.get(position);
                Intent intent = new Intent(MainActivity.this, ContactDetail.class);
                intent.putExtra("name", contact.getName());
                intent.putExtra("phone", contact.getPhone());
                intent.putExtra("email", contact.getEmail());
                intent.putExtra("id", contact.getId());
                startActivity(intent);
            }
        });

        FloatingActionButton fab = findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.d("MainActivity", "touch in");
                Intent intent_add = new Intent(MainActivity.this, AddContact.class);
                startActivity(intent_add);
            }
        });
    }

    private void initContacts() {
        LitePal.getDatabase();
        List<Contact> contacts= LitePal.findAll(Contact.class);
        for(Contact contact : contacts) {
            Log.d("MainActivity", "Contact name is " + contact.getName());
            contact.setImageId(R.drawable.contact9);
            contactList.add(contact);
        }
    }
}
